<?php

namespace app\modules\backend\controllers;

use app\models\Base;
use app\models\Auth;
use app\models\AuthItemChild;
use app\models\UserLogin;
use app\tools\Re;
use Yii;
use yii\helpers\ArrayHelper;
use app\models\Admin;
header('Access-Control-Allow-Origin: *');

class PermissionController extends BaseController
{
    public function actionAuthList()
    {
        $page = Yii::$app->request->get('page', 0);
        $query = Auth::find()->where(['type' => 2, 'permission_type' => 1]);
        $auth = $query->limit(Auth::PAGE_SIZE)->offset($page*Auth::PAGE_SIZE)->orderBy("sort asc")->all();
        $fields = ['name', 'description', 'sort', 'parent_name', 'permission_type', 'created_at'];
        return Re::data([
            'data' => Base::buildParamsList($auth, $fields),
            'totalPage' => $query->count(),
            'currentPage' => $page,
            'perPage' => Auth::PAGE_SIZE
        ]);
    }

    public function actionCreateAuth()
    {
        $post = Yii::$app->request->post();
        if (empty($post['name']) || empty($post['description'])) {
            return Re::data(null, '缺少参数', Re::ERROR);
        }
        $auth = Auth::find()->where(['name' =>$post['name'], 'type' => 2])->one();
        if ($auth) {
            return Re::data(null, '权限已存在', Re::ERROR);
        }
        $auth = new Auth();
        $auth->name = $post['name'];
        $auth->description = $post['description'];
        $auth->type = 2;
        $auth->sort = $post['sort'];
        $auth->parent_name = $post['parent_name'];
        $auth->permission_type = $post['permission_type'];
        $auth->created_at = time();
        $auth->save();
        $authItemChild = new AuthItemChild();
        $authItemChild->parent = "超级管理员";
        $authItemChild->child = $post['name'];
        $authItemChild->permission_type = $post['permission_type'];
        if (!$authItemChild->save()) {
          return Re::data(null, $authItemChild->showErrors(), Re::ERROR);
        }
        return Re::data();
    }

    public function actionDeleteAuth()
    {
        $name = Yii::$app->request->post('name');
        $auth = Auth::find()->where(['name' =>$name, 'type' => 2])->one();
        if ($auth) {
            $auth->delete();
            AuthItemChild::deleteAll(['child' => $name]);
            return Re::data();
        }
        return Re::data(null, '权限不存在', Re::ERROR);
    }

    public function actionSelectData(){
        $list = Auth::find()->where(['type' => 2, 'permission_type' => 1])->andWhere("name <> 'privilege_list'")->orderBy("sort asc")->all();
        return Re::data(['data' => $list]);
    }

    public function actionGetRoleAuth(){
        $post = Yii::$app->request->post();
        if (empty($post['name'])) {
            return Re::data(null, '缺少参数', Re::ERROR);
        }
        $list = Auth::find()
        ->leftJoin("auth_item_child", "auth_item.name = auth_item_child.child")
        ->where(['parent'=>$post['name']])
        ->select("name,description,sort")
        ->orderBy("sort asc")
        ->all();
        return Re::data(['data' => $list]);
    }

    public function actionGetUserAuth(){
        $user_token = Yii::$app->request->get("user_token");
        $user_id = 0;
        if (empty($user_token)) {
            return Re::data(null, '缺少参数', Re::ERROR);
        }
        if (preg_match('/^Bearer\s+(.*?)$/', $user_token, $matches)) {
            $user_token = $matches[1];
        }
        $user_login = UserLogin::find()->where(['token' => $user_token])->orderBy("created_at desc")->one();
        if ($user_login) {
            $user_id = $user_login->user_id;
            $list = AuthItemChild::find()
            ->leftJoin("auth_assignment", "auth_assignment.item_name = auth_item_child.parent")
            ->where(['auth_assignment.user_id'=>$user_id, 'permission_type' => 1])
            ->select("child")
            ->column();
            return Re::data(['data' => $list]);
        }
        return Re::data(['data' => []]);
    }

    //权限树数据源
    public function actionTreeData(){
      $role_name = Yii::$app->request->post("name");
      $auth_assign = [];
      if ($role_name) {//如果传递角色，需要读取该角色已分配的权限，同时权限树数据源中已分配的权限需要设置checked属性
        $auth_assign = AuthItemChild::find()->where(['parent' => $role_name])->select("child")->column();
      }
      $page_permission_list = Auth::find()->where(['type' => 2, 'permission_type' => 1])->andWhere("name <> 'privilege_list'")->orderBy("sort asc")->all();
      $page_permission_data = [];
      if ($page_permission_list) {
        foreach ($page_permission_list as $v) {
          $button_permission_list = Auth::find()->where(['type' => 2, 'permission_type' => 2, 'parent_name' => $v->name])->orderBy("sort asc")->all();
          $button_permission_data = [];
          if ($button_permission_list) {
            foreach ($button_permission_list as $v1) {
              $checked = false;
              $button_permission_data[] = [
                'title' => $v1->description,
                'key' => $v1->name,
                'checked' => in_array($v1->name, $auth_assign)
              ];
            }
          }
          $page_permission_data[] = [
            'title' => $v->description,
            'key' => $v->name,
            'expand' => $button_permission_data ? true : false,
            'checked' => in_array($v->name, $auth_assign),
            'children' => $button_permission_data
          ];
        }
      }
      return Re::data(['data' => $page_permission_data]);
    }

    //根据页面权限获取按钮权限
    public function actionPageBtnPermission(){
      $parent_name = Yii::$app->request->post("parent_name");
      $button_permission_list = Auth::find()->where(['type' => 2, 'permission_type' => 2, 'parent_name' => $parent_name])->all();
      $fields = ['name', 'description', 'sort', 'parent_name', 'permission_type', 'created_at'];
      return Re::data([
          'data' => Base::buildParamsList($button_permission_list, $fields)
      ]);
    }

    //获取用户已分配的按钮权限
    public function actionChildBtnPermission(){
      $parent_name = Yii::$app->request->post("parent_name");
      $button_permission_arr = Auth::find()->where(['type' => 2, 'permission_type' => 2, 'parent_name' => $parent_name])->select("name")->column();
      $data = [];
      if ($button_permission_arr) {
        $data = AuthItemChild::find()
        ->leftJoin("auth_assignment", "auth_assignment.item_name = auth_item_child.parent")
        ->where(['auth_assignment.user_id' => Yii::$app->user->id, 'child' => $button_permission_arr])
        ->select("child")
        ->column();
      }
      return Re::data(['data' => $data]);
    }
}
